import { ref } from 'vue';
import { isEqual } from 'lodash';

export function useRequestData() {
  // 获取缓存数据，更新数据
  const getRequestData = (pageData, storageKey, requestCallBack) => {
    const storageData = localStorage.getItem(storageKey);
    try {
      storageData && (pageData.value = JSON.parse(storageData));
    } catch {
      console.error('getRequestData方法异常')
    }
    requestCallBack();
  }

  // 验证新老数据是否相同
  const isEqualFn = (oldDataKey, newData) => {
    const oldData = localStorage.getItem(oldDataKey);
    try {
      // 是否存在缓存数据 && 数据（数组、对象）是否一致 
      if (oldData && oldData != 'undefined' && isEqual(JSON.parse(oldData), newData)) {
        return false;
      }
      localStorage.setItem(oldDataKey, JSON.stringify(newData));
      return true;
    } catch {
      console.error('缓存数据出错' + oldDataKey, oldData)
      return false;
    }
  }

  return {
    getRequestData,
    isEqualFn
  }
}